<!-- src/components/admin/schedule-modal.vue -->
<template>
  <u-popup :show="S.showModal.value" mode="center" :round="10">
    <view class="vbox popup-container">
      <view class="popup-header">
        <text>{{
          S.modalMode.value === "edit" ? "编辑课堂" : "添加课堂"
        }}</text>
        <view class="fill"></view>
        <u-icon name="close" @click="S.closePopup()" size="18"></u-icon>
      </view>
      <u-form :model="S.currentModel" ref="formRef" :rules="rules" label-position="left">
        <!-- 课堂名称 -->
        <u-form-item label="课堂名称" prop="name">
          <u-input v-model="S.currentModel.name" placeholder="输入课堂名称"></u-input>
        </u-form-item>

        <!-- 邀请码 -->
        <u-form-item label="邀请码" prop="invitationCode">
          <u-input v-model="S.currentModel.invitationCode" placeholder="输入邀请码"></u-input>
        </u-form-item>

        <!-- 按钮 -->
        <view class="hbox">
          <u-button type="default" @click="S.closePopup()" text="取消"></u-button>
          <u-button type="primary" @click="handleSubmit" :text="S.modalMode.value === 'edit' ? '保存' : '添加'"></u-button>
        </view>
      </u-form>
    </view>
  </u-popup>
</template>

<script setup>
import { ref, watch } from "vue";
import S from "@/js/admin/schedule.js";

const formRef = ref();

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: "请输入课堂名称", trigger: ["blur", "change"] },
  ],
  invitationCode: [
    { required: true, message: "请输入邀请码", trigger: ["blur", "change"] },
  ],
});

// 监听模态框状态变化，重置表单验证
watch(
  () => S.showModal.value,
  (newVal) => {
    if (!newVal) {
      // 模态框关闭时重置表单验证
      formRef.value?.resetValidation?.();
    }
  }
);

const handleSubmit = () => {
  formRef.value.validate().then(() => {
    S.handleSubmit();
  }).catch(errors => {
    console.error("表单校验失败:", errors);
    uni.showToast({ title: '请检查输入内容', icon: 'none' });
  });
};
</script>

<style scoped>
.popup-container {
  padding: 20px;
  width: 80vw;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.fill {
  flex: 1;
}

.hbox {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.hbox u-button {
  flex: 1;
}
</style>